package com.funsolution.taskhey.manager.person;

import java.util.Date;

import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.EntityExistsException;
import javax.transaction.Transactional;
import javax.transaction.Transactional.TxType;

import com.funsolution.taskhey.dao.person.PersonDao;
import com.funsolution.taskhey.domain.Person;

@Stateless
public class PersonManagerImpl implements PersonManager {

    private PersonDao personDao;

    @Transactional(value = TxType.REQUIRES_NEW, rollbackOn = { EntityExistsException.class })
    @Override
    public Person save(Person person) {
	Person existingPerson = personDao.findByUsername(person.getUsername());
	if (existingPerson != null) {
	    existingPerson.setFirstName(person.getFirstName());
	    existingPerson.setSecondName(person.getSecondName());
	    existingPerson.setPassword(person.getPassword());
	    existingPerson.setDateUpdated(new Date());
	    existingPerson.setBirthDate(person.getBirthDate());
	    return existingPerson;
	}
	return personDao.save(person);
    }

    @Inject
    public void setPersonDao(PersonDao personDao) {
	this.personDao = personDao;
    }

    @Override
    public Person findByUsername(String username) {

	return personDao.findByUsername(username);
    }

    @Override
    public Person findByUsernameOrEmail(String username, String password) {
	
	return personDao.findByUsernameOrPassword(username, password);
    }
}
